package User

import (
	"Yoj/internal/dao"
	"context"
	"fmt"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/glog"

	"Yoj/api/User/Verify"
	"Yoj/internal/controller/Auther"
)

type UserLoginInfo struct {
	UserId   uint
	Username string
	Email    string
	Password string
}

func (c *ControllerVerify) MainUserVerify(ctx context.Context, req *Verify.MainUserVerifyReq) (res *Verify.MainUserVerifyRes, err error) {
	// 获取用户信息
	usermodel := dao.YUser.Ctx(ctx).Fields(dao.YUser.Columns().UserId, dao.YUser.Columns().Username, dao.YUser.Columns().Email, dao.YUser.Columns().Password)
	userinfo := &UserLoginInfo{}

	switch req.Nametag {
	case "name":
		err = g.Validator().Rules("passport").Data(req.Username).Run(ctx)
		if err != nil {
			return nil, gerror.NewCode(gcode.CodeInvalidParameter, fmt.Sprintf("Username参数:%s 不合法;", req.Username))
		}
		err = usermodel.Where("username = ?", req.Username).Scan(userinfo)
	case "qid":
		err = g.Validator().Rules("length:6,11").Data(req.Username).Run(ctx)
		if err != nil {
			return nil, gerror.NewCode(gcode.CodeInvalidParameter, fmt.Sprintf("Username参数:%s 不合法", req.Username))
		}
		err = usermodel.Where("user_id = ?", req.Username).Scan(userinfo)
	case "email":
		err = g.Validator().Rules("email").Data(req.Username).Run(ctx)
		if err != nil {
			return nil, gerror.NewCode(gcode.CodeInvalidParameter, fmt.Sprintf("Username参数:%s 不合法", req.Username))
		}
		err = usermodel.Where("email = ?", req.Username).Scan(userinfo)
	default:
		return nil, gerror.NewCode(gcode.CodeInvalidParameter, fmt.Sprintf("nametag参数: %s不合法", req.Nametag))
	}

	if (userinfo == nil) || err != nil {
		glog.Error(ctx, err)
		return nil, gerror.NewCode(gcode.CodeInvalidParameter, "用户不存在")
	}

	// 判断密码是否正确
	if userinfo.Password != req.UserPwd {
		return nil, gerror.NewCode(gcode.CodeInvalidParameter, "用户名或密码错误")
	}

	auther := Auther.NewAuthToken(ctx)
	token, _ := auther.GenerateToken(userinfo.UserId)

	res = &Verify.MainUserVerifyRes{
		Qid:   userinfo.UserId,
		Name:  userinfo.Username,
		Token: token,
	}

	return res, nil
}
